<template>
  <div class="page-content" v-loading="loading">
    <h5 class="text-center">签约登记表</h5>
    <table class="table table-sm table-bordered vertical-align-middle text-center">
      <tbody>
        <tr>
          <td width="17%">客户名称</td>
          <td width="33%">{{ related.customer_name || '' }}</td>
          <td width="17%">客户类型</td>
          <td width="33%">{{ orgClassName }}</td>
        </tr>
        <tr>
          <td>担保额度</td>
          <td>
            {{ +related.reply_funds || +entrustContract.reply_funds || related.apply_funds }}万元
          </td>
          <td>担保期限</td>
          <td>{{ entrustContract.load_years || related.months }} 月</td>
        </tr>
        <tr>
          <td>担保费率</td>
          <td>{{ entrustContract.gua_rate || '-' }}%</td>
          <td>贷款利率</td>
          <td>{{ entrustContract.load_rate || '-' }}%</td>
        </tr>
        <tr>
          <td>放款机构</td>
          <td>{{ entrustContract.bank_name || related.bank_name || '-' }}</td>
          <td>贷款品种</td>
          <td>{{ loadVarietiesStr }}</td>
        </tr>
        <tr>
          <td>贷款实际用途</td>
          <td colspan="3" class="text-left">{{ related.funds_use_dir || '' }}</td>
        </tr>
        <tr>
          <td>签约登记方式</td>
          <td colspan="3" class="text-left pl-5">
            <el-radio-group v-model="approval.is_online_sign" :disabled="isView" class="my-radio">
              <el-radio label="1">在线签约</el-radio>
              <el-radio label="2">线下签约</el-radio>
            </el-radio-group>
          </td>
        </tr>
        <tr>
          <td>签约登记</td>
          <template v-if="+approval.is_online_sign === 2">
            <td colspan="3" class="text-left">
              <div class="d-flex justify-content-between align-items-center">
                <div class="flex-2 pl-2">1、现场签约照片</div>
                <div class="flex-2" :class="attachStatus.class">
                  {{ attachStatus.label }}
                  <el-button type="text" @click="handleAttach">
                    <i class="fa" :class="`fa-${isView ? 'search' : 'gavel'}`"></i>
                  </el-button>
                </div>
              </div>
            </td>
          </template>
          <template v-else>
            <td colspan="3" class="text-left">
              <div class="d-flex justify-content-between align-items-center">
                <div class="flex-1 pl-2">1、客户签约状态</div>
                <div class="flex-2 d-flex align-items-center">
                  <div :class="contractSignStatus ? contractStatus.class : 'text-warning'">
                    {{ contractSignStatus ? contractStatus.label : '待客户签约' }}
                  </div>
                  <ul class="list-inline flex-1">
                    <li class="list-inline-item">
                      <el-button
                        type="text"
                        class="col-md-4 col-sm-12"
                        @click="handleCopy(customerUrl)"
                      >
                        <i class="fa fa-link"></i>
                        复制链接
                      </el-button>
                    </li>
                    <li class="list-inline-item">
                      <el-popover placement="top-start" title="客户签约地址" trigger="hover">
                        <div>
                          <qr-code :value="customerUrl" :size="140"></qr-code>
                        </div>
                        <el-button slot="reference" class="col-md-4 col-sm-12" type="text">
                          <i class="fa fa-qrcode"></i>
                          扫描二维码
                        </el-button>
                      </el-popover>
                    </li>
                  </ul>
                </div>
              </div>
              <div class="text-danger ml-4 font-weight-bold">
                <div>
                  点击完成登记后客户开始签约（登记后扫描签约没有合同，可能合同正在生成等待一两分钟后刷新一下）
                </div>
                扫码或打开链接后使用贷款主体手机号({{ related.mobile_no }})登录，密码初始值({{
                  related.mobile_no
                }})。
              </div>
            </td>
          </template>
        </tr>
      </tbody>
    </table>
    <!-- <div class="text-warning text-sm">
      <div>选择线上点击保存后客户才能开始签约。（项目经理待办）</div>
      <div>选择线下则可跳过客户签约 ，进行放款申请，在放款申请上传相关合同文件即可。</div>
      <div>部分合同走线下需联系系统管理员，手动触发放款流程</div>
    </div> -->
    <contract-attachment
      :visible.sync="attachVisible"
      @success="getAttachMent"
      :view-mode="isView"
      :query-id="queryId"
      :attach-name="attachName"
      :parent-tag="parentTag"
      :attach-data="attachment"
    ></contract-attachment>

    <div class="text-center pt-2" v-if="!isView">
      <el-button
        class="btn-long"
        :loading="buttonLoading"
        @click="handleRegister"
        v-if="+approval.is_online_sign === 2"
        type="primary"
      >
        完成登记
      </el-button>
      <el-button
        v-else
        class="btn-long"
        type="primary"
        @click="handleSendRegister"
        :loading="buttonLoading"
      >
        完成登记
      </el-button>
      <el-button class="btn-long" :loading="buttonLoading" type="danger" @click="handleClose">
        取消
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { copyText, arrayFromString } from '@vimi/utils-tool'

import {
  enumLoanVarieties,
  getContractData,
  updateContract,
  addContract,
} from '@/credit/views/city/self/components/contractApprove/index'

import ContractAttachment from '@/credit/views/city/self/components/contractRegistr/ContractAttachment'

export default {
  components: {
    ContractAttachment,
  },
  props: {
    viewMode: {
      type: Boolean,
      default: true,
    },
    queryId: String,
  },
  data() {
    return {
      loading: false,
      parentTag: '签约附件',
      attachName: '签约现场',
      attachment: [],
      attachVisible: false,
      buttonLoading: false,
      approval: {},
      enumContractStatus: {
        0: { label: '未发送', css: 'danger' },
        2: { label: '待签章', css: 'info' },
        3: { label: '已签章', css: 'success' },
      },
      related: {},
    }
  },

  computed: {
    ...mapGetters(['entrustContract', 'enumOrgClassObj', 'guardDatas']),
    orgClassName() {
      return this.enumOrgClassObj[this.related.org_class]
    },
    customerUrl() {
      return window.location.origin + '/credit-h5/#/'
    },
    // 合同期间
    loadPeriod() {
      return (
        (this.entrustContract.load_date || '- ') +
        '至' +
        (this.entrustContract.load_end_date || ' -')
      )
    },
    // 贷款品种
    loadVarietiesStr() {
      return enumLoanVarieties[this.entrustContract.loan_varieties] || ''
    },
    attachStatus() {
      return {
        status: this.attachment.length ? 1 : 0,
        label: this.attachment.length ? '已处理' : '未处理',
        class: this.attachment.length ? 'text-success' : 'text-danger',
      }
    },
    contractStatus() {
      const contractStatus = this.enumContractStatus[this.related.contract_approval_status] || {}
      return {
        status: this.related.contract_approval_status,
        label: contractStatus.label,
        class: `text-${contractStatus.css}`,
      }
    },
    isView() {
      return this.viewMode
    },
    contractSignStatus() {
      const isSign =
        this.guardDatas.find(item => +(item.sign_status || '') < 2) ||
        +(this.entrustContract.sign_status || '') < 2
      return !isSign
    },
  },
  watch: {
    queryId: {
      handler: function () {
        this.$store.dispatch('getEnumOrgClass')
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  methods: {
    handleCopy(value) {
      const success = copyText(value)
      if (success) {
        this.$message.success('已复制到粘贴板')
      } else {
        this.$message.error('已复制到粘贴失败')
      }
    },
    // getSignAddress() {
    //   window.location.href = this.customerUrl
    // },
    handleClose() {
      this.$emit('close', false)
    },
    setNotice() {
      this.$emit('reget', true)
    },
    handleAttach() {
      this.attachVisible = true
    },
    handleSendRegister() {
      this.buttonLoading = true
      Promise.all([
        this.approval.contract_approval_id
          ? updateContract(this.approval.contract_approval_id, {
              is_online_sign: this.approval.is_online_sign,
            })
          : addContract({
              is_online_sign: this.approval.is_online_sign,
              service_id: this.related.service_id,
              customer_related_id: this.queryId,
            }),
      ])
        .then(() => {
          this.$message.success('已完成签约登记')
          this.$emit('success', true)
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.buttonLoading = false
        })
    },
    handleRegister() {
      // if (+this.attachStatus.status === 0) {
      //   return this.$message.warning('请先完成签约登记内容！')
      // }
      this.buttonLoading = true
      Promise.all([
        this.approval.contract_approval_id
          ? updateContract(this.approval.contract_approval_id, {
              is_online_sign: this.approval.is_online_sign,
            })
          : addContract({
              is_online_sign: this.approval.is_online_sign,
              service_id: this.related.service_id,
              customer_related_id: this.queryId,
            }),
      ])
        .then(() => {
          this.$message.success('已完成签约登记')
          this.$emit('success', true)
        })
        .catch(err => {
          this.$message.error(err?.data?.error_description || '提交失败，请重试！')
        })
        .finally(() => {
          this.buttonLoading = false
        })
    },
    getData() {
      if (!this.queryId) {
        return
      }
      this.loading = true
      Promise.all([
        this.getRelated(),
        this.$store.dispatch('getEntrustContract', this.queryId),
        this.$store.dispatch('getGuardsData', this.queryId),
        this.getContractApprove(),
        this.getAttachMent(),
      ]).finally(() => {
        this.loading = false
      })
    },
    getRelated() {
      this.$api
        .getData(this.$serviceName, 'customer_related', { 'customer_related_id.eq': this.queryId })
        .then(res => {
          this.related = res?.data?.[0] ?? {}
        })
    },
    getContractApprove() {
      return getContractData(this.queryId).then(res => {
        this.approval = res
      })
    },
    getAttachMent() {
      this.attachment = []
      return this.$api
        .getData(
          this.$serviceName,
          'datum_customer_attachment',
          {
            'file_type.eq': 1,
            'customer_related_id.eq': this.queryId,
            'attachment_type.eq': this.attachName,
          },
          { create_time: 'asc' }
        )
        .then(res => {
          const data = res?.data ?? []
          data.forEach(item => {
            const images = arrayFromString(item.attachment).map(img => {
              return { url: img, id: item.id, attachment: item.attachment }
            })
            this.attachment.push(...images)
          })
        })
    },
  },
}
</script>
<style lang="scss" scoped>
.my-radio /deep/ .el-radio__inner {
  position: relative;
  border-radius: 0px;
  &::after {
    border-radius: 0px;
    box-sizing: content-box;
    content: '';
    border: 1px solid #fff;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(1);
    width: 3px;
    transition: transform 0.15s ease-in 0.05s;
    transform-origin: center;
    background-color: unset;
  }
}

.my-radio /deep/ .is-disabled.is-checked .el-radio__inner {
  position: relative;
  border-radius: 0px;
  background: blue;
  &::after {
    border-radius: 0px;
    box-sizing: content-box;
    content: '';
    border: 1px solid white;
    border-left: 0;
    border-top: 0;
    height: 7px;
    left: 4px;
    position: absolute;
    top: 1px;
    transform: rotate(45deg) scaleY(1);
    width: 3px;
    transition: transform 0.15s ease-in 0.05s;
    transform-origin: center;
    background-color: unset;
  }
}
.my-radio /deep/ .is-disabled + span.el-radio__label {
  color: unset;
}
.page-content {
  padding: 2rem;
  max-width: 900px;
  margin: 0 auto;
  line-height: 2rem;
}
.vertical-align-middle td {
  vertical-align: middle;
}
.flex-2 {
  flex: 2;
}

.text-sm {
  font-size: 0.6rem;
}
</style>
